package cn.lsoft.undoner.util;

/**
 * <A HREF="mailto:undoner@gmail.com">undoner</A>
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
    protected DefaultHttpClient client;
    private String useAgent = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:18.0) Gecko/20100101 Firefox/18.0";
    private String accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    private int maxTotal = 100;
    private int defaultMaxPerRoute = 20;
    private int connectionTimeout = '鱀';
    private int soTimeout = 300000;
    private boolean handler_redirects = true;
    private static final long SLEEP_INTERVAL = 3000L;
    private int retryTime = 3;

    public HttpClientUtil() {
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager();
        manager.setDefaultMaxPerRoute(this.defaultMaxPerRoute);
        manager.setMaxTotal(this.maxTotal);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(manager);
        defaultHttpClient.setHttpRequestRetryHandler((HttpRequestRetryHandler)null);
        this.client = defaultHttpClient;
        this.client.getParams().setIntParameter("http.socket.timeout", this.soTimeout);
        this.client.getParams().setIntParameter("http.connection.timeout", this.connectionTimeout);
        this.client.getParams().setParameter("http.protocol.handle-redirects", Boolean.valueOf(this.handler_redirects));
    }

    private void setHeader(HttpRequestBase method) {
        method.setHeader("User-Agent", this.useAgent);
        method.setHeader("Accept", this.accept);
        method.setHeader("Connection", "keep-alive");
    }

    public String httpDelete(String url) {
        String str = null;
        HttpDelete method = null;

        for(int i = 0; i < this.retryTime; ++i) {
            try {
                if(i > 0) {
                    Thread.currentThread();
                    Thread.sleep(3000L);
                }

                method = new HttpDelete(url);
                this.setHeader(method);
                HttpResponse e = this.client.execute(method);
                int responseCode = e.getStatusLine().getStatusCode();
                HttpEntity entity = e.getEntity();
                if(entity != null) {
                    if(responseCode != 200) {
                        log.warn(url + " Http code when send HttpGet : " + responseCode + " --> RETRY TIME : " + (i + 1) + ", respones body : " + EntityUtils.toString(entity, "UTF-8"));
                        continue;
                    }

                    str = EntityUtils.toString(entity, "UTF-8");
                }

                if(StringUtils.isNotBlank(str)) {
                    String var8 = str;
                    return var8;
                }
            } catch (Exception var12) {
                log.error("Error occurred when send HttpDelete: " + url, var12);
            } finally {
                if(method != null && !method.isAborted()) {
                    method.abort();
                }

                method.releaseConnection();
            }
        }

        return null;
    }

    public String httpGet(String url) {
        String str = new String();
        HttpGet method = null;

        for(int i = 0; i < this.retryTime; ++i) {
            try {
                if(i > 0) {
                    Thread.currentThread();
                    Thread.sleep(3000L);
                }

                method = new HttpGet(url);
                this.setHeader(method);
                HttpResponse e = this.client.execute(method);
                int responseCode = e.getStatusLine().getStatusCode();
                HttpEntity entity = e.getEntity();
                if(entity != null) {
                    if(responseCode != 200) {
                        log.warn(url + " Http code when send HttpGet : " + responseCode + " --> RETRY TIME : " + (i + 1) + ", respones body : " + EntityUtils.toString(entity, "UTF-8"));
                        continue;
                    }

                    str = EntityUtils.toString(entity, "UTF-8");
                }

                if(StringUtils.isNotBlank(str)) {
                    String var8 = str;
                    return var8;
                }
            } catch (Exception var12) {
                log.error("Error occurred when send HttpGet: " + url, var12);
            } finally {
                if(method != null && !method.isAborted()) {
                    method.abort();
                }

                method.releaseConnection();
            }
        }

        return null;
    }

    public boolean download(String path, String url) {
        HttpGet method = null;

        for(int i = 0; i < this.retryTime; ++i) {
            try {
                if(i > 0) {
                    Thread.currentThread();
                    Thread.sleep(3000L);
                }

                method = new HttpGet(url);
                this.setHeader(method);
                HttpResponse e = this.client.execute(method);
                int responseCode = e.getStatusLine().getStatusCode();
                HttpEntity entity = e.getEntity();
                if(responseCode == 200 && entity != null) {
                    File storeFile = new File(path);
                    FileOutputStream output = new FileOutputStream(storeFile);
                    InputStream input = entity.getContent();
                    byte[] b = new byte[1024];
                    boolean j = false;

                    int var19;
                    while((var19 = input.read(b)) != -1) {
                        output.write(b, 0, var19);
                    }

                    output.flush();
                    output.close();
                    boolean var18 = true;
                    return var18;
                }

                log.warn(url + " Http code when send HttpGet : " + responseCode + " --> RETRY TIME : " + (i + 1) + ", respones body : " + EntityUtils.toString(entity, "UTF-8"));
            } catch (Exception var16) {
                log.error("Error occurred when send HttpGet: " + url, var16);
            } finally {
                if(method != null && !method.isAborted()) {
                    method.abort();
                }

                method.releaseConnection();
            }
        }

        return false;
    }

    public String httpPost(String url, Map<String, String> parameter) {
        return this.httpPost(url, (Map)parameter, (String)null);
    }

    public String httpPost(String url, Map<String, String> parameter, String encodeCharset) {
        String responseBody = null;
        HttpPost post = null;

        for(int i = 0; i < this.retryTime; ++i) {
            try {
                if(i > 0) {
                    Thread.currentThread();
                    Thread.sleep(3000L);
                }

                post = new HttpPost(url);
                ArrayList e = new ArrayList();
                Iterator response = parameter.entrySet().iterator();

                while(response.hasNext()) {
                    Entry entity = (Entry)response.next();
                    e.add(new BasicNameValuePair((String)entity.getKey(), (String)entity.getValue()));
                }

                post.setEntity(new UrlEncodedFormEntity(e, encodeCharset == null?"UTF-8":encodeCharset));
                HttpResponse var16 = this.client.execute(post);
                HttpEntity var17 = var16.getEntity();
                if(var17 != null) {
                    if(var16.getStatusLine().getStatusCode() != 200) {
                        log.warn(url + " Http code when send HttpGet : " + var16.getStatusLine().getStatusCode() + " --> RETRY TIME : " + (i + 1) + ", respones body : " + EntityUtils.toString(var17, "UTF-8"));
                        continue;
                    }

                    responseBody = EntityUtils.toString(var17, "UTF-8");
                }

                if(StringUtils.isNotBlank(responseBody)) {
                    String var10 = responseBody;
                    return var10;
                }
            } catch (Exception var14) {
                log.error("Error occurred when send HttpPost: " + url, var14);
            } finally {
                if(post != null && !post.isAborted()) {
                    post.abort();
                }

                post.releaseConnection();
            }
        }

        return responseBody;
    }

    public String httpPost(String url, String postData) {
        return this.httpPost(url, postData, (String)null, (String)null);
    }

    public String httpPost(String url, String postData, String encodeCharset, String contentType) {
        contentType = contentType == null?"application/json":contentType;
        String responseBody = null;
        HttpPost post = null;

        for(int i = 0; i < this.retryTime; ++i) {
            try {
                if(i > 0) {
                    Thread.sleep(3000L);
                }

                post = new HttpPost(url);
                post.setHeader("Content-Type", contentType);
                post.setEntity(new StringEntity(postData, encodeCharset == null?"UTF-8":encodeCharset));
                HttpResponse e = this.client.execute(post);
                HttpEntity entity = e.getEntity();
                if(entity != null) {
                    if(e.getStatusLine().getStatusCode() != 200) {
                        log.warn(url + " Http code when send HttpGet : " + e.getStatusLine().getStatusCode() + " --> RETRY TIME : " + (i + 1) + ", respones body : " + EntityUtils.toString(entity, "UTF-8"));
                        continue;
                    }

                    responseBody = EntityUtils.toString(entity, "UTF-8");
                }

                if(StringUtils.isNotBlank(responseBody)) {
                    String var10 = responseBody;
                    return var10;
                }
            } catch (Exception var14) {
                log.error("Error occurred when send HttpPost: " + url, var14);
            } finally {
                if(post != null && !post.isAborted()) {
                    post.abort();
                }

                post.releaseConnection();
            }
        }

        return responseBody;
    }

    public String httpPost(String url, File file, String contentType) {
        contentType = contentType == null?"application/file":contentType;
        String responseBody = null;
        HttpPost post = null;

        for(int i = 0; i < this.retryTime; ++i) {
            try {
                if(i > 0) {
                    Thread.sleep(3000L);
                }

                post = new HttpPost(url);
                post.setHeader("Content-Type", contentType);
                post.setEntity(new FileEntity(file));
                HttpResponse e = this.client.execute(post);
                HttpEntity entity = e.getEntity();
                if(entity != null) {
                    if(e.getStatusLine().getStatusCode() != 200) {
                        log.warn(url + " Http code when send HttpPost : " + e.getStatusLine().getStatusCode() + " --> RETRY TIME : " + (i + 1) + ", respones body : " + EntityUtils.toString(entity, "UTF-8"));
                        continue;
                    }

                    responseBody = EntityUtils.toString(entity, "UTF-8");
                }

                if(StringUtils.isNotBlank(responseBody)) {
                    String var9 = responseBody;
                    return var9;
                }
            } catch (Exception var13) {
                log.error("Error occurred when send HttpPost: " + url, var13);
            } finally {
                if(post != null && !post.isAborted()) {
                    post.abort();
                }

                post.releaseConnection();
            }
        }

        return responseBody;
    }

    public String getUseAgent() {
        return this.useAgent;
    }

    public void setUseAgent(String useAgent) {
        this.useAgent = useAgent;
    }

    public String getAccept() {
        return this.accept;
    }

    public void setAccept(String accept) {
        this.accept = accept;
    }

    public int getConnectionTimeout() {
        return this.connectionTimeout;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
        if(null != this.client) {
            this.client.getParams().setIntParameter("http.connection.timeout", connectionTimeout);
        }

    }

    public int getSoTimeout() {
        return this.soTimeout;
    }

    public void setSoTimeout(int soTimeout) {
        this.soTimeout = soTimeout;
        if(null != this.client) {
            this.client.getParams().setIntParameter("http.socket.timeout", soTimeout);
        }

    }

    public boolean isHandler_redirects() {
        return this.handler_redirects;
    }

    public void setHandler_redirects(boolean handler_redirects) {
        this.handler_redirects = handler_redirects;
        if(null != this.client) {
            this.client.getParams().setParameter("http.protocol.handle-redirects", Boolean.valueOf(handler_redirects));
        }

    }

    public static void main(String[] args) {
        HttpClientUtil client = new HttpClientUtil();
        System.out.println(client.httpPost("http://206.99.94.201:80/TVAds/videocapture", "{\"type\":\"video\",\"channelUuid\":\"44abc47e-7785-11e3-97c1-12313f002953\",\"beginTimestamp\":1411080072000,\"endTimestamp\":1411080087000}"));
    }

    public void finalize() throws Throwable {
        super.finalize();
        this.client.getConnectionManager().shutdown();
    }

    public int getMaxTotal() {
        return this.maxTotal;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public int getDefaultMaxPerRoute() {
        return this.defaultMaxPerRoute;
    }

    public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {
        this.defaultMaxPerRoute = defaultMaxPerRoute;
    }

    public int getRetryTime() {
        return this.retryTime;
    }

    public void setRetryTime(int retryTime) {
        this.retryTime = retryTime;
    }
}
